<template>
    <div>
        <el-card class="box-card">
            <!-- 卡片顶部添加品牌按钮 -->
            <el-button type="primary" size="default" icon="Plus" @click="showAddDialog"
                v-has="`btn.Trademark.add`">添加</el-button>
            <!-- 表格组件：用于展示已有得平台数据 -->
            <!-- table:---border:可以设置表格纵向是否有边框
                table-column:---label:某一个列表 ---width:设置这列宽度 ---align:设置这一列对齐方式    
            -->
            <el-table style="margin:10px 0px" border :data="tableValuekArr">
                <el-table-column label="顺序" width="80px" align="center" prop="position"></el-table-column>
                <!-- table-column:默认展示数据用div -->
                <el-table-column label="名称" prop="name"></el-table-column>
                <el-table-column label="链接" prop="linkUrl"></el-table-column>
                <el-table-column label="状态" width="80px">
                    <template #="{ row, $index }">
                        <el-icon :color="row.visible === 1 ? 'green' : 'orange'">
                            <component :is="row.visible === 1 ? 'View' : 'Hide'"></component>
                        </el-icon>
                    </template>
                </el-table-column>
                <el-table-column label="位置">
                    <template #="{ row, $index }">
                        <span v-if="row.recommend === 0">首页</span>
                        <span v-else>推荐位</span>
                    </template>
                </el-table-column>
                <el-table-column label="轮播图">
                    <template #="{ row, $index }">
                        <img :src="row.imgUrl" style="width:35px;height: 35px;cursor: pointer;" @click="previewImage(row)">
                    </template>
                </el-table-column>
                <el-table-column label="更新时间" prop="createTime"></el-table-column>
                <el-table-column label="操作" width="120px">
                    <template #="{ row, $index }">
                        <el-button type="primary" size="small" icon="Edit" @click="update(row)"></el-button>
                        <el-popconfirm :title="`您确定要删除${row.name}?`" width="250px" icon="Delete" @confirm='remove(row.id)'>
                            <template #reference>
                                <el-button type="warning" size="small" icon="Delete"></el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 对话框组件:在添加品牌与修改已有品牌的业务时候使用结构 -->
        <!-- 
            v-model:属性用户控制对话框的显示与隐藏的 true显示 false隐藏
             title:设置对话框左上角标题
        -->
        <el-dialog v-model="dialogFormVisible" :title="formParams.id ? '修改' : '添加'">
            <el-form style="width: 80%;" :model="formParams" :rules="rules" ref="formRef" label-width="100px">
                <el-form-item label="名称" prop="name">
                    <el-input placeholder="请输入轮播图名称" v-model="formParams.name"></el-input>
                </el-form-item>
                <el-form-item label="轮播图" prop="imgUrl">
                    <!-- upload组件属性:action图片上传路径书写/api,代理服务器不发送这次post请求  -->
                    <el-upload class="avatar-uploader" action="/api/v1/m/upload" :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload" :on-preview="handlePictureCardPreview">
                        <img v-if="formParams.imgUrl" :src="formParams.imgUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="链接" prop="linkUrl">
                    <el-input placeholder="轮播图链接" v-model="formParams.linkUrl"></el-input>
                </el-form-item>
                <el-form-item label="顺序" prop="position">
                    <el-input placeholder="轮播图顺序，1,2,3" v-model="formParams.position"></el-input>
                </el-form-item>
                <el-form-item label="位置" prop="recommend">
                    <el-radio-group v-model="formParams.recommend" class="ml-4">
                        <el-radio :label="0" size="large">首页</el-radio>
                        <el-radio :label="1" size="large">推荐位</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="状态" prop="visible">
                    <el-radio-group v-model="formParams.visible" class="ml-4">
                        <el-radio :label='1' size="large">隐藏</el-radio>
                        <el-radio :label='0' size="large">显示</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <!-- 具名插槽:footer -->
            <template #footer>
                <el-button type="primary" size="default" @click="cancel">取消</el-button>
                <el-button type="primary" size="default" @click="confirm">确定</el-button>
            </template>
        </el-dialog>

        <el-dialog v-model="img_dialogVisible">
            <img :style="{ width: '100%' }" :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ElMessage, UploadProps, formEmits } from 'element-plus'
//引入组合式API函数ref
import { ref, onMounted, reactive, nextTick } from 'vue';
import { reqBannersList, reqAddOrUpdateBanner, reqDeleteBanner } from '@/api/content/facade';
import type { TBanner,Records } from '@/api/content/facade/type'

let img_dialogVisible = ref<boolean>(false)
let dialogImageUrl = ref('')

//存储已有品牌的数据
let tableValuekArr = ref<Records>([]);
//控制对话框显示与隐藏
let dialogFormVisible = ref<boolean>(false)
//定义收集新增品牌数据
let formParams = reactive<TBanner>({
    name: '',
    imgUrl: '',
    linkUrl: '',
    visible: 0,
    position: 0,
    recommend: 0,
})
//获取el-form组件实例
let formRef = ref();
//获取已有品牌的接口封装为一个函数:在任何情况下向获取数据,调用次函数即可
const getBannersList = async (pager = 1) => {
    //当前页码
    let result: any = await reqBannersList();
    if (result.code == 0) {
        tableValuekArr.value = result.data;
    }
}
//组件挂载完毕钩子---发一次请求,获取第一页、一页三个已有品牌数据
onMounted(() => {
    getBannersList();
});

const resetForms = () => {
    formParams.id = 0;
    formParams.name = '';
    formParams.imgUrl = '';
    formParams.linkUrl = ''
    formParams.visible = 0
    formParams.position = 0
    formParams.recommend = 0
}
//添加品牌按钮的回调
const showAddDialog = () => {
    //对话框显示
    dialogFormVisible.value = true;
    //清空收集数据
    resetForms()
    //第一种写法:ts的问号语法
    // formRef.value?.clearValidate('tmName');
    // formRef.value?.clearValidate('logoUrl');
    nextTick(() => {
        if (formRef.value) {
            formRef.value.clearValidate('name');
            formRef.value.clearValidate('imgUrl');
        }
    })
}
//修改已有品牌的按钮的回调
//row:row即为当前已有的品牌
const update = (row: TBanner) => {
    //清空校验规则错误提示信息
    nextTick(() => {
        if (formRef.value) {
            formRef.value.clearValidate('name');
            formRef.value.clearValidate('imgUrl');
        }
    })
    //对话框显示
    dialogFormVisible.value = true;
    //ES6语法合并对象
    Object.assign(formParams, row);
}
//对话框底部取消按钮
const cancel = () => {
    //对话框隐藏
    dialogFormVisible.value = false;
}
const confirm = async () => {
    //在你发请求之前,要对于整个表单进行校验
    //调用这个方法进行全部表单相校验,如果校验全部通过，在执行后面的语法
    await formRef.value.validate();
    console.log(formRef.value)
    let result: any = await reqAddOrUpdateBanner(formParams);
    //添加|修改已有品牌
    if (result.code == 0) {
        //关闭对话框
        dialogFormVisible.value = false;
        //弹出提示信息
        ElMessage({
            type: 'success',
            message: formParams.id ? '修改成功' : '添加成功'
        });
        //再次发请求获取已有全部的品牌数据
        getBannersList();
    } else {
        //添加品牌失败
        ElMessage({
            type: 'error',
            message: formParams.id ? '修改失败' : '添加失败'
        });
        //关闭对话框
        dialogFormVisible.value = false;
    }
}
//上传图片组件->上传图片之前触发的钩子函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    //钩子是在图片上传成功之前触发,上传文件之前可以约束文件类型与大小
    //要求:上传文件格式png|jpg|gif 4M
    if (rawFile.type == 'image/png' || rawFile.type == 'image/jpeg' || rawFile.type == 'image/gif') {
        if (rawFile.size / 1024 / 1024 < 4) {
            return true;
        } else {
            ElMessage({
                type: 'error',
                message: '上传文件大小小于4M'
            })
            return false;
        }
    } else {
        ElMessage({
            type: 'error',
            message: "上传文件格式务必PNG|JPG|GIF"
        })
        return false;
    }
}
//图片上传成功钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
    //response:即为当前这次上传图片post请求服务器返回的数据
    //收集上传图片的地址,添加一个新的品牌的时候带给服务器
    formParams.imgUrl = response.data.url;
    //图片上传成功,清除掉对应图片校验结果
    formRef.value.clearValidate('imgUrl');

}

//品牌自定义校验规则方法
const validatorTmName = (rule: any, value: any, callBack: any) => {
    //是当表单元素触发blur时候,会触发此方法
    //自定义校验规则
    if (value.trim().length >= 2) {
        callBack();
    } else {
        //校验未通过返回的错误的提示信息
        callBack(new Error('名称位数大于等于两位'))
    }
}
//品牌LOGO图片的自定义校验规则方法
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
    //如果图片上传
    if (value) {
        callBack();
    } else {
        callBack(new Error('LOGO图片务必上传'))
    }
}

//表单校验规则对象
const rules = {
    name: [
        //required:这个字段务必校验,表单项前面出来五角星
        //trigger:代表触发校验规则时机[blur、change]
        { required: true, trigger: 'blur', validator: validatorTmName }
    ],
    imgUrl: [
        { required: true, validator: validatorLogoUrl }
    ]
}
//气泡确认框确定按钮的回调
const remove = async (id: number) => {
    //点击确定按钮删除已有品牌请求
    let result = await reqDeleteBanner(id);
    if (result.code == 0) {
        //删除成功提示信息
        ElMessage({
            type: 'success',
            message: '删除成功'
        });
        //再次获取已有的品牌数据
        getBannersList();
    } else {
        ElMessage({
            type: 'error',
            message: '删除失败'
        })
    }
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    console.log(uploadFile)
    //   dialogImageUrl.value = uploadFile.url!
    //   dialogVisible.value = true
}

const previewImage=(row:TBanner)=>{
    img_dialogVisible.value=true
    dialogImageUrl.value = row.imgUrl
}
</script>
<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>